
package com.bluelinelabs.conductor.demo.controllers;

import com.bluelinelabs.conductor.conductor.manager.ObjectManager;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import com.bluelinelabs.conductor.conductor.RouterTransaction;
import com.bluelinelabs.conductor.conductor.changehandler.HorizontalChangeHandler;
import com.bluelinelabs.conductor.conductor.utile.TextUtils;
import com.bluelinelabs.conductor.demo.ResourceTable;
import com.bluelinelabs.conductor.demo.callback.ScreenOrirentaionChange;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.slice.MainAbilitySlice;
import com.bluelinelabs.conductor.demo.util.CallBackManager;
import com.bluelinelabs.conductor.demo.util.PxUtils;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;

/**
 * lipeiquan
 *
 * @since 2021-05-06
 */
public class TargetDisplayController extends BaseController implements TargetTitleEntryController.TargetTitleEntryControllerListener, ScreenOrirentaionChange {

    private static final int REQUEST_SELECT_IMAGE = 126;
    private String selectedText = null;
    private Uri imageUri = Uri.parse("content://media/external/images/media");
    private PixelMap pixelMap;

    public TargetDisplayController() {
        super(ResourceTable.Layout_controller_target_display);
    }

    @Override
    public void onViewCreated(Component component) {
        title = "Target Controller Demo";
        registerForActivityResult(REQUEST_SELECT_IMAGE);
        ObjectManager.getInstance().setIdTitleAboutSetVisibility(Component.HIDE);
        setTextView();
        if(pixelMap != null){
            setImageView();
        }


        component.findComponentById(ResourceTable.Id_pick_title_button).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(ohos.agp.components.Component component) {
                getRouter().pushController(
                    RouterTransaction.with(new TargetTitleEntryController(TargetDisplayController.this))
                        .pushChangeHandler(new HorizontalChangeHandler())
                        .popChangeHandler(new HorizontalChangeHandler())
                );
            }
        });

        component.findComponentById(ResourceTable.Id_pick_image_button).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(ohos.agp.components.Component component) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.GET_CONTENT");
                intent.setUri(imageUri);
                intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
                intent.setType("image/*");
                ((AbilitySlice) getActivity()).startAbilityForResult(intent, REQUEST_SELECT_IMAGE);

            }
        });
        onOrientationChanged();
        CallBackManager.registerScreenOrirentaionChange(this);
    }

    private void setTextView() {
        if (getView() == null) {
            return;
        }
        if (!TextUtils.isEmpty(selectedText)) {
            ((Text) getView().findComponentById(ResourceTable.Id_selection)).setText(selectedText);
        } else {
            ((Text) getView().findComponentById(ResourceTable.Id_selection)).setText("Press pick title to set this title, or pick image to fill in the image view.");
        }
    }

    private void setImageView() {
        if (getView() == null) {
            return;
        }
        pixelMap = getPixelMapByImagePath(displayPic(imageUri));
        if (pixelMap != null) {
            ((Image) getView().findComponentById(ResourceTable.Id_image_view)).setPixelMap(pixelMap);
        }
    }

    @Override
    public void onTitlePicked(String option) {
        selectedText = option;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && data.getUri() != null) {
            imageUri = data.getUri();
            setImageView();
        }
    }


    //Uri转file
    public FileDescriptor displayPic(Uri ur) {
        if (ur == null) {
            return null;
        }
        DataAbilityHelper helper = DataAbilityHelper.creator(getActivity());
        try {
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, "" + ur.getLastPath());
            FileDescriptor filedesc = helper.openFile(uri, "r");
            //  ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
            // decodingOpts.desiredSize = new Size(300, 300);
            // ImageSource imageSource = ImageSource.create(filedesc, null);
            //  PixelMap pixelMap = imageSource.createThumbnailPixelmap(decodingOpts, true);

            return filedesc;
        } catch (DataAbilityRemoteException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    //
    public PixelMap getPixelMapByImagePath(FileDescriptor filedesc) {
        if (filedesc == null) {
            return null;
        }
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        sourceOptions.formatHint = "image/png";
        ImageSource cacheImageSource = ImageSource.create(filedesc, sourceOptions);
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.editable = true;
        PixelMap pixelMap = cacheImageSource.createPixelmap(decodingOptions);
        return pixelMap;
    }


    @Override
    public void onOrientationChanged() {

        int displayOrientation = ((MainAbilitySlice) getActivity()).getDisplayOrientation();
        switch (displayOrientation){
            case 0:
            case 2:
                getView().findComponentById(ResourceTable.Id_image_view).setWidth((int)(PxUtils.dp2px(200)));
                getView().findComponentById(ResourceTable.Id_image_view).setHeight((int)(PxUtils.dp2px(200)));
                getView().findComponentById(ResourceTable.Id_image_view).setMarginsLeftAndRight((int)(PxUtils.dp2px(24)),(int)(PxUtils.dp2px(24)));
                getView().findComponentById(ResourceTable.Id_image_view).setMarginsTopAndBottom((int)(PxUtils.dp2px(24)),(int)(PxUtils.dp2px(24)));
                break;
            case 1:
            case 3:
                getView().findComponentById(ResourceTable.Id_image_view).setWidth((int)(PxUtils.dp2px(120)));
                getView().findComponentById(ResourceTable.Id_image_view).setHeight((int)(PxUtils.dp2px(120)));
                getView().findComponentById(ResourceTable.Id_image_view).setMarginsLeftAndRight((int)(PxUtils.dp2px(16)),(int)(PxUtils.dp2px(16)));
                getView().findComponentById(ResourceTable.Id_image_view).setMarginsTopAndBottom((int)(PxUtils.dp2px(16)),(int)(PxUtils.dp2px(16)));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CallBackManager.unRegisterScreenOrirentaionChange(this);
    }
}
